package dse.messages.singleversion;

import dse.*;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;
import dse.messages.multiversion.VersionReader;

public class SendVersionMessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private VersionReader reader;
	private Version version;
	
	public SendVersionMessageHandler(Experiment experiment, DataObject dobj, Version version, 
			VersionReader reader){
		super(experiment);
		this.dobj = dobj;
		this.version = version;
		this.reader = reader;
	}

	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		if(ExperimentRecorder.debug)
			recorder.debug(this, "msgIntrpt: " + message, time);
		reader.readVersion(recorder, -1, time);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		if(ExperimentRecorder.debug)
			recorder.debug(this, "Received: " + message, time);
		if (message.messageType() != MessageType.SendVersion) {
			recorder.warn(
					"SendVersionMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}			
		Node receiver = message.to();
		
		// Does the receiver have the share?
		DataShare share = receiver.getDataShare(dobj);
		if (share != null)
		{
			share.addVolatileVersion(version);
			Message m = super.createMACResponseMessage(receiver, message.from(), dobj, 
					version.getSequence(), message.purpose(), reader);
			if(ExperimentRecorder.debug)
				recorder.debug(this, "new msg: " + m, time);
			experiment.messageQueue().enqueueMessage(m, time);
		}
		else
		{
			this.messageInterupted(recorder, message, time);
		}
	}
}
